<template>
	<view class="sku-select">
		<view class="item" v-for="(list, listIndex) in skuList" :key="listIndex">
			<view class="item-title">{{ list.name }}</view>
			<view class="item-wrapper">
				<view
					class="item-content"
					@tap="skuClick(item, listIndex, index)"
					v-for="(item, index) in list.muster"
					:key="index"
					:class="[
						item.count > 0 ? '' : 'disabled',
						item.isActive ? 'active' : '',
					]"
				>
					{{ item.name }}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
/**
 * SkuSelect sku选择
 * @property {Array} list sku列表参数
 * @property {Array} selectArr sku已选中数据
 * @event {Function} skuClick sku元素点击事件
 * @example <skuList :list="skuList" :selectArr="selectArr"></skuList>
 */
export default {
	props: {
		list: {
			type: Array,
			default: function () {
				return [];
			},
		},
		selectArr: {
			type: Array,
			default: function () {
				return [];
			},
		},
	},
	data() {
		return {
			skuList: [],
			skuSelect: [],
			count: this.selectArr.length,
		};
	},
	watch: {
		// 监听props变化
		list(val) {
			this.skuList = val;
			this.skuSelect = this.selectArr;
		},
	},
	created() {
		// 初始化复制props中数据
		this.skuList = this.list;
		this.skuSelect = this.selectArr;
	},
	methods: {
		// sku元素选择
		skuClick(item, listIndex, index) {
			const that = this;
			const originActive = item.isActive;

			// 判断元素是否有库存可以选择
			if (item.count > 0) {
				// 获取sku数据的第一级
				const itemAttr = that.skuList[listIndex].muster;
				itemAttr.filter((v, i) => {
					v.isActive = false;
					if (index === i) {
						that.skuSelect.filter((v2, i) => {
							// 判断是否已经选中过，去重
							if (v.parentId === v2.parentId) {
								that.skuSelect.splice(i, 1);
								that.count--;
							}
						});
						if (originActive) {
							v.isActive = false;
						} else {
							v.isActive = true;
							that.$set(that.skuSelect, that.count++, v);
						}
					}
				});

				that.$emit('skuSelect', that.skuSelect);
			} else {
				uni.showToast({
					title: '暂无库存',
					duration: 800,
					icon: 'none',
				});
				return false;
			}
		},
	},
};
</script>

<style lang="scss">
.sku-select {
	padding: $uni-spacing-base $uni-spacing-base $uni-spacing-sm;
	.item {
		margin: 0 0 8rpx;
	}
	.item-wrapper {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
	}
	.item-title {
		margin: 0 0 16rpx;
		font-size: 25rpx;
		text-align: center;
	}
	.item-content {
		border: 1px solid #ccc;
		padding: 4rpx 24rpx;
		margin: 0 12rpx 24rpx;
		border-radius: 3px;
		font-size: 25rpx;
		color: #999;
		min-width: 60rpx;
		text-align: center;
		&.active {
			background: $ds-main-color;
			border: 1px solid $ds-main-color;
			color: #fff;
		}

		&.disabled {
			border: 1px solid #eee;
			background: #eee;
			color: #999;
		}
	}
}
</style>
